<template>
  <div class="page-login page-account">
    <div class="logo">
      <img src="@/assets/images/logo.png" alt="运动嘉">
    </div>
    <section class="form-section">
      <div class="form-item">
        <div class="label">手机号</div>
        <van-field
          class="form-field"
          v-model="phone"
          placeholder="请输入手机号"
          maxlength="11"
          v-validate="'required|phone'"
          name="phone"
        />
      </div>
      <div class="form-item">
        <div class="label">密码</div>
        <van-field
          class="form-field"
          v-model="password"
          :type="passwordType"
          placeholder="请输入密码"
          :icon="passwordIcon"
          @click-icon="changeVisible"
          name="password"
          v-validate="'required'"
          @keyup.enter="submitEvent"
        />
      </div>
      <div class="action-box">
          <router-link class="forget" :to="{name: 'forget'}">忘记密码？</router-link>
      </div>
      <van-button @click="submitEvent" class="submit-button" type="primary" size="large" :disabled="submitStatus" :loading="submitStatus">登录</van-button>
      <div class="goregist">新用户？<router-link :to="{name: 'regist'}" class="goto">注册</router-link></div>
    </section>
  </div>
</template>

<script>
import { API_LOGIN } from '@/service/account'
import { wxjsdkMixin } from '@/components/mixins'
export default {
  mixins: [wxjsdkMixin],
  name: 'login',
  data () {
    return {
      phone: '',
      password: '',
      passwordVisible: false,
      submitStatus: false
    }
  },
  computed: {
    passwordType () {
      return this.passwordVisible ? 'text' : 'password'
    },
    passwordIcon () {
      return this.passwordVisible ? 'password-view' : 'password-not-view'
    }
  },
  mounted () {
    this.wechatHideMenu()
  },
  methods: {
    changeVisible () {
      this.passwordVisible = !this.passwordVisible
    },
    submitEvent () {
      this.$validator.validate().then(result => {
        if (result) {
          this.submitStatus = true
          let reqData = {
            phone: this.phone,
            password: this.password
          }
          API_LOGIN(reqData).then(resData => {
            let { access_token, refresh_token, userId, nickname, headImagerUrl, phoneNum } = resData
            this.$store.dispatch('saveToken', { access_token, refresh_token })
            this.$store.dispatch('saveUserInfo', {
              nickname,
              userId,
              phoneNum,
              headImagerUrl
            })
            this.$toast('登录成功')
            this.$router.replace({
              name: 'home'
            })
          }).catch(() => {
            this.submitStatus = false
          })
        } else {
          this.$toast(this.errors.all()[0])
        }
      })
    }
  }
}
</script>

<style lang="less">
@import "../../assets/styles/account.less";
</style>
